//
//  ZWStatusesViewModel.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/20.
//  Copyright © 2016年 flyiron. All rights reserved.
// ->ZWHomeTableViewController

import UIKit

class ZWStatusesListViewModel: NSObject {
    
//    var statusList: [ZWStatuses]?
    var max_id: Int64 = 0
    var since_id: Int64 = 0
    var statusViewModelList: [ZWStatusesViewModel]?
    func loadData(isPull: Bool,finished:(isSucess:Bool) -> ()) {
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        if isPull{
            //代表上拉加载
            max_id = statusViewModelList?.last?.status?.id ?? 0
            if max_id != 0{
                max_id -= 1
            }
        }else{
            //代表下拉刷新
            since_id = statusViewModelList?.first?.status?.id ?? 0
        }
        let parameters = [
            "access_token":ZWUserInfoViewModel.sharedViewModel.accessToken!,
            "max_id":"\(max_id)",
            "since_id":"\(since_id)"
            
        ]
        ZWNetworkTools.sharedTools.request(urlString: url, parameters: parameters) { (responseObject, error) -> () in
//            print(responseObject)
            if error != nil {
                print("获取数据失败")
                finished(isSucess: false)
                return
            }
            guard let dicts = responseObject as? [String : AnyObject] else {
                print("返回的数据不是字典")
                finished(isSucess: false)
                return
            }
            
            guard let dict = dicts["statuses"] as? [[String : AnyObject]] else{
                finished(isSucess: false)
                return
            }
            
            var tempArr:[ZWStatusesViewModel] = [ZWStatusesViewModel]()
            
            for value in dict {
                let statusViewModel = ZWStatusesViewModel()
                let status = ZWStatuses(dict: value)
                statusViewModel.status = status
                tempArr.append(statusViewModel)
                
            }
            if self.statusViewModelList == nil {
                self.statusViewModelList = tempArr
            }
            if isPull{
                self.statusViewModelList = self.statusViewModelList! + tempArr
            }else{
                self.statusViewModelList = tempArr + self.statusViewModelList!
                   print("请求回来\(tempArr.count)条数据")
            }
            
         
           finished(isSucess: true)
            
        }
        
    }
}
